<?php
namespace app\controller\api;

use app\BaseController;
use app\model\GoodsModel;
use app\model\OrderCommentModel;
use app\model\OrderModel;
use app\Request;
use app\validate\OrderCommentValidate;
use think\facade\Db;

/**
 * 订单相关接口
 * @package app\controller\api
 */

class Order extends BaseController
{
    // 支付订单
    public function payOrder(Request $request)
    {
        $orderId = input('order_id/d', '');
        $payType = input('pay_type/d', '');
        if (!$orderId || !$payType) {
            $this->error('参数错误');
        }
        if ($payType != 4) {
            $this->error('暂不支持此支付方式，请使用余额支付');
        }
        $order = OrderModel::find($orderId);
        if (empty($order)) {
            $this->error('订单不存在');
        }
        if ($order->status != 0) {
            $this->error('该订单已支付');
        }
        // 查询用户余额
        $userWallet = Db::name('user')
            ->where('user_id', '=',$request->user_id)
            ->value('wallet');
        if ($userWallet < $order->final_price) {
            $this->error('余额不足');
        }
        // 开启事务
        Db::startTrans();

        // 修改订单信息
        $order->status = 1;
        $order->pay_time = date('Y-m-d H:i:s');
        $order->pay_type = $payType;
        $editOrderInfo = $order->save();
        // 扣款
        $dec = Db::name('user')
            ->where('user_id', '=',$request->user_id)
            ->dec('wallet', $order->final_price)
            ->update();

        if ($editOrderInfo && $dec) {
            Db::commit();
            $this->success('支付成功');
        } else {
            Db::rollback();
            $this->error('支付失败');
        }
    }

    // 创建订单
    public function createOrder(Request $request)
    {
        $data = input();
        // 验证器验证

        // 查询商品
        $goods = GoodsModel::find($data['goods_id']);
        if (empty($goods)) {
            $this->error('商品不存在');
        }
        // 判断库存是否充足
        if ($data['num'] > $goods['store_num']) {
            $this->error('库存不足');
        }

        // 去商品表查询
        $freight = 10;
        $discount = 0;

        // 计算实付款
        $total = (($goods['now_price'] * $data['num']) - $discount) + $freight;
        if ($total < 0) {
            $total = 0;
        }

        $insert_data = [
            'user_id' => $request->user_id,
            'goods_id' => $data['goods_id'],
            'num' => $data['num'],
            'sku' => $data['sku'],
            'freight' => $freight,
            'discount' => $discount,
            'final_price' => $total,
            'remarks' => $data['remarks'],
            'trade_no' => $this->createTradeNo(),
            'address_id' => $data['address_id'],
            'status' => 0,
        ];

        // 入库
        $model = new OrderModel();
        if ($model->save($insert_data)) {
            $this->success('订单创建成功');
        }
        $this->error('订单创建失败');
    }

    // 创建交易订单号
    private function createTradeNo()
    {
        return date('YmdHis') . mt_rand(0000000, 9999999);
    }

    // 评价订单
    public function commentOrder(Request $request)
    {
        $data = input();
        // 验证数据
        $validate = new OrderCommentValidate();
        $result = $validate->scene('comment')->check($data);
        if (!$result) {
            $this->error($validate->getError());
        }
        $data['user_id'] = $request->user_id;
        $model = new OrderCommentModel();
        if ($model->save($data)) {
            $this->success('评价成功');
        }
        $this->error('评价失败');
    }
}
